import Layout from "@/layout/index.vue";
import type { RouteRecordRaw } from "vue-router";
import Demo from "@/views/demo/index.vue";
import router from ".";
import { useUserStore } from "@/store/useUserStore";
import { useLocationParams } from "@/store/useLocationStore";
import { isSameDomain, objToQueryString } from "@/utils/url";
import { domain, useAuthStore, initDomain } from "@/store/useAuthStore";
import { isWeChatBrowserPro } from "@/utils/wechat";
import useLiveDataStore from "@/views/LiveNew/stores/LiveDataStore";
import {
  handleAuth,
  handleCountDown,
  handleCountDownIM,
  handleEntry,
  handleLiveIM,
  checkReplay,
  handleWatchLive,
  handleWatchLiveReplay,
  handleEntryCheck
} from "./routerHook";

const liveNewRoutes = [
  {
    path: "live",
    name: "LiveCourse",
    component: () => import("@/layout/live.vue"),
    redirect: { name: "Live" },
    meta: { title: "直播" },
    async beforeEnter(to) {
      const { query } = to;
      if (query.oPd === "1" && query.pd && to.name !== "LiveCheckPassword") {
        return {
          name: "LiveCheckPassword",
          query: { ...query, redirect: to.name }
        };
      }
      if (to.meta.noAuth) {
        return true;
      } else {
        if (handleAuth(to)) {
          return false;
        }
      }
      return true;
    },
    children: [
      {
        path: "",
        name: "Live",
        component: () => import("@/views/LiveNew/Live.vue"),
        props: route => ({ roomId: route.query.rId || route.query.roomId }),
        meta: { title: "直播", needEntry: true },
        beforeEnter: [
          handleEntryCheck,
          handleEntry,
          handleCountDown,
          checkReplay,
          handleLiveIM,
          handleWatchLive
        ]
      },
      {
        path: "live-replay",
        name: "LiveReplay",
        component: () => import("@/views/LiveNew/LiveReplay.vue"),
        props: route => ({ roomId: route.query.rId || route.query.roomId }),
        meta: { title: "直播回放", needEntry: true },
        beforeEnter: [
          handleEntryCheck,
          handleEntry,
          handleLiveIM,
          handleWatchLiveReplay
        ]
      },
      {
        path: "/live-check-password",
        name: "LiveCheckPassword",
        component: () => import("@/components/auth/CheckPassword.vue"),
        meta: { title: "请输入直播间密码", noAuth: true },
        props: route => ({
          redirect: route.query.redirect
        })
      },
      {
        path: "live-countdown",
        name: "LiveCountdown",
        component: () => import("@/views/LiveNew/CountDown.vue"),
        meta: { title: "直播倒计时", needEntry: true },
        beforeEnter: [
          handleEntryCheck,
          handleEntry,
          checkReplay,
          handleCountDownIM
        ]
      },
      // {
      //   path: "live-replay-countdown",
      //   name: "LiveReplayCountdown",
      //   component: () => import("@/views/LiveNew/LiveReplayCountDown.vue"),
      //   meta: { title: "直播回放倒计时", needEntry: true },
      //   beforeEnter: [handleEntry, checkReplay]
      // },
      {
        path: "live-course-error",
        name: "LiveCourseError",
        component: () => import("@/views/live/Error.vue"),
        meta: { title: "链接错误" }
      },
      {
        path: "live-end",
        name: "LiveEnd",
        component: () => import("@/views/LiveNew/LiveEnd.vue"),
        meta: { title: "直播结束", needEntry: true },
        // beforeEnter: [handleEntry]
      }
    ]
  }
];
// const liveCourseRoutes = [
//   {
//     path: "live-course-error",
//     name: "LiveCourseError",
//     component: () => import("@/views/live/Error.vue"),
//     meta: { title: "链接错误" }
//   },
//   {
//     path: "live",
//     name: "LiveCourse",
//     component: () => import("@/views/live/index.vue"),
//     meta: { title: "直播" },
//     props: route => ({ roomId: route.query.rId || route.query.roomId }),
//     async beforeEnter(to, from) {
//       const { query } = to;
//       if (query.oPd === "1" && query.pd && from.name !== "LiveCheckPassword") {
//         router.push({ name: "LiveCheckPassword", query });
//         return false;
//       }
//       if (handleAuth(to)) {
//         return false;
//       }
//       return true;
//     }
//   },
//   {
//     path: "live-course-countdown",
//     name: "LiveCourseCountdown",
//     component: () => import("@/views/live/CourseCountdown.vue"),
//     meta: { title: "直播倒计时" }
//   },
//   {
//     path: "live-course-detail",
//     name: "LiveCourseDetail",
//     component: () => import("@/views/live/CourseDetail.vue"),
//     meta: { title: "直播详情" }
//   },
//   {
//     path: "live-check-password",
//     name: "LiveCheckPassword",
//     component: () => import("@/views/live/CheckPassword.vue"),
//     meta: { title: "请输入直播间密码", noAuth: true }
//   }
// ];
const courseRoutes = [
  {
    path: "course-error",
    name: "CourseError",
    component: () => import("@/views/course/Error.vue"),
    meta: { title: "链接错误" }
  },
  {
    path: "course",
    name: "Course",
    component: () => import("@/views/course/index.vue"),
    meta: { title: "课程" },
    props: route => ({ roomId: route.query.rId || route.query.roomId }),
    async beforeEnter(to, from) {
      const { query } = to;
      if (query.oPd === "1" && query.pd && from.name !== "CheckPassword") {
        router.push({ name: "CheckPassword", query });
        return false;
      }
      if (handleAuth(to)) {
        return false;
      }
      return true;
    }
  },
  {
    path: "course-countdown",
    name: "CourseCountdown",
    component: () => import("@/views/course/CourseCountdown.vue"),
    meta: { title: "课程倒计时" }
  },
  {
    path: "course-detail",
    name: "CourseDetail",
    component: () => import("@/views/course/CourseDetail.vue"),
    meta: { title: "课程详情" }
  },
  {
    path: "check-password",
    name: "CheckPassword",
    component: () => import("@/views/course/CheckPassword.vue"),
    meta: { title: "请输入课程密码", noAuth: true }
  },
  {
    path: "live-end",
    name: "LiveEnd",
    component: () => import("@/views/live/LiveEnd.vue"),
    meta: { title: "直播结束" }
  }
];
const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    name: "root",
    component: Layout,
    async beforeEnter(to) {
      if (!domain) {
        await initDomain();
      }
      // 安全域名，或者不需要登陆的页面
      if (isSameDomain() || to.meta.noAuth) {
        return true;
      }
      // 只有在经销商域名，且to需要登陆的时候
      const { code, ...otherQuery } = to.query;
      if (code) {
        const { removeParam, getAllParams } = useLocationParams();
        removeParam("code");
        const { login } = useUserStore();
        const data = await login({ ...getAllParams(), code });
        if (data) {
          return { name: to.name, query: otherQuery };
        } else {
          return false;
        }
      }
      return true;
    },
    // redirect: { name: "Course" },
    children: [
      {
        path: "/home",
        name: "Home",
        component: () => import("@/views/index.vue")
      },
      {
        path: "demo",
        name: "Demo",
        component: Demo,
        meta: {
          title: "主页"
        }
      },
      {
        path: "tools",
        name: "Tools",
        component: () => import("@/views/tools/index.vue"),
        meta: {
          title: "工具"
        }
      },
      {
        path: "about",
        name: "About",
        component: () => import("@/views/about/index.vue"),
        meta: {
          title: "关于",
          noCache: true
        }
      },
      {
        path: "questionnaire",
        name: "Questionnaire",
        component: () => import("@/views/questionnaire/index.vue"),
        meta: { title: "问卷" }
      },
      {
        path: "question",
        name: "Question",
        component: () => import("@/views/course/Question.vue"),
        meta: { title: "课程问答" }
      },
      {
        path: "red-packet",
        name: "RedPacket",
        component: () => import("@/views/course/RedPacket.vue"),
        meta: { title: "红包" }
      },
      {
        path: "sign-in",
        name: "SignIn",
        component: () => import("@/views/course/SignIn.vue"),
        meta: { title: "签到" }
      },
      {
        path: "login",
        name: "Login",
        component: () => import("@/views/login/index.vue"),
        meta: { title: "登录", noAuth: true },
        beforeEnter(to, from) {
          // 兼容安全域名端
          if (isSameDomain()) {
            const { code, from } = to.query;
            if (from && code) {
              const { removeParam, getAllParams } = useLocationParams();
              removeParam("from");
              const fromUrl = `${from}?${objToQueryString(getAllParams())}`;
              window.location.href = decodeURIComponent(fromUrl);
              return false;
            }
          } else {
            handleAuth(from);
            return false;
          }
          return true;
        }
      },
      {
        path: "check-password",
        name: "CheckPassword",
        component: () => import("@/views/course/CheckPassword.vue"),
        meta: { title: "请输入课程密码", noAuth: true }
      },
      {
        path: "error",
        name: "Error",
        component: () => import("@/views/error/index.vue"),
        meta: { title: "错误", noAuth: true },
        beforeEnter(to, from) {
          to.params.from = from as any;
          return true;
        }
      },
      {
        path: "auth",
        name: "Auth",
        component: () => import("@/views/auth/index.vue"),
        meta: { title: "授权", noAuth: true }
      },
      {
        path: "register",
        name: "Register",
        component: () => import("@/views/register/index.vue"),
        meta: { title: "注册", noAuth: true },
        async beforeEnter(to) {
          if (!to.query.code) {
            await useAuthStore().handleAuth(to);
            return false;
          }
          return true;
        }
      },
      {
        path: "link",
        name: "Link",
        component: () => import("@/views/link/index.vue"),
        meta: { title: "会员认证" },
        async beforeEnter(to) {
          if (!isWeChatBrowserPro()) {
            if (to.query.auth) {
              await useUserStore().auth(to.query.auth);
              router.replace({ name: "Entry", query: { ...to.query } });
              return false;
            }
          } else {
            if (handleAuth(to)) {
              return false;
            }
          }
          return true;
        }
      },
      {
        path: "reward",
        name: "Reward",
        component: () => import("@/views/reward/index.vue")
      },
      {
        path: "entry",
        name: "Entry",
        component: () => import("@/views/entry/index.vue"),
        meta: { title: "首页" }
      },
      {
        path: "course-list",
        name: "CourseList",
        component: () => import("@/views/course/List.vue"),
        meta: { title: "课程列表" }
      },
      {
        path: "train-list",
        name: "TrainList",
        component: () => import("@/views/train/List.vue"),
        meta: { title: "课程列表" }
      },
      {
        path: "train-sub-list",
        name: "TrainSubList",
        component: () => import("@/views/train/SubList.vue"),
        meta: { title: "课节列表" }
      },
      // ...liveCourseRoutes,
      ...courseRoutes,
      ...liveNewRoutes
    ]
  }
];

export default routes;
